package com.collabscm.pf.vo;

import java.util.Collection;
import java.util.Iterator;

import com.collabscm.pf.util.JsonUtils;


/**
 * 失败的响应内容
 *
 * @author Zeng Raoxing
 */
public class FailureResponse extends AjaxResponse {
	private static final long serialVersionUID = 1L;
	public static final String VALIDATION_FAILURE = "validationFailure";
	public static final String VERSION_CONFLICT = "versionConflict";
	/**
	 * 失败类型，包括：数据验证失败、版本冲突。
	 */
	private String failureType;
	/**
	 * 失败原因
	 */
	private Object cause;

	public FailureResponse() {
		super(FAILURE);
	}
	
	public String getFailureType() {
		return failureType;
	}

	public void setFailureType(String failureType) {
		this.failureType = failureType;
	}

	public Object getCause() {
		return cause;
	}

	public void setCause(Object cause) {
		this.cause = cause;
	}
	
	/**
	 * 此为经常使用的JSON串，因此通过自定义过toJSONString的方法来实现，避免使用默认反射方式实现。
	 */
	@Override
	public String toJSONString() {
		StringBuffer sb = new StringBuffer("{resultType:\"").append(getResultType()).append("\",");
		sb.append("failureType:\"").append(failureType).append("\", cause:");
		if(cause instanceof Collection<?>) {
			Iterator<?> itr = ((Collection<?>) cause).iterator();
			sb.append("[");
			while(itr.hasNext()) {
				sb.append(JsonUtils.toJsonObjectString(itr.next())).append(",");
			}
			sb.deleteCharAt(sb.length() - 1); //删除最后一个逗号
			sb.append("]");
		} else if(cause instanceof String){
			sb.append("\"").append(cause).append("\"");
		}
		sb.append("}");
		return sb.toString();
	}

}
